package com.ustcinfo.ishare.esClient;

import com.ustcinfo.ishare.utils.XmlProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.*;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by Shinelon on 2017/12/27.
 */
public class HttpConnES {
    private static final Logger LOGGER = LoggerFactory.getLogger(HttpConnES.class);

    private HttpURLConnection conn;
    private volatile boolean inited = false;

    private String transport_addresses;
    private static String es_username;
    private static String es_password;

    class MyAuthenticator extends Authenticator {
        @Override
        public PasswordAuthentication getPasswordAuthentication() {
            return (new PasswordAuthentication(es_username, es_password.toCharArray()));
        }
    }

    public synchronized HttpURLConnection init(String indexName,String type,int symbol) throws Exception {
        if (!inited) {
            String url = null;
            Map<String, String> config = XmlProperties.loadFromXml("elasticsearch.xml");
            if (config == null) {
                LOGGER.error("load xml err");
                System.out.println("配置文件为空！");
                return null;
            }
            Iterator<Map.Entry<String, String>> iterator = config.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, String> next = iterator.next();
                if (next.getKey().equals("es.username")) {
                    es_username = next.getValue();
                }
                if (next.getKey().equals("es.password")) {
                    es_password = next.getValue();
                }

                if (next.getKey().equals("transport.addresses")) {
                    transport_addresses = next.getValue();
                }
            }
            // 获取权限
            Authenticator.setDefault(new MyAuthenticator());
            if (symbol==0){
                //POST查询
                url = "http://"+transport_addresses.split(":")[0]+":9200"+"/"+indexName+"/"+type+"/_search";
            }else if (symbol==1){
                //统计文档数量
                url = "http://"+transport_addresses.split(":")[0]+":9200"+"/"+indexName+"/"+type+"/_count";
            }else if (symbol==2){
                //统计所有索引
                url = "http://"+transport_addresses.split(":")[0]+":9200/_cat/indices?v";
            }else{
                //GET查询
                url = "http://"+transport_addresses.split(":")[0]+":9200"+"/"+indexName+"/"+type+"/_search";
            }
            System.out.println(url);
            URL realUrl = new URL(url);
            conn = (HttpURLConnection) realUrl.openConnection();
            if (symbol==0){
                //POST查询
                conn.setRequestMethod("POST");
            }else if (symbol==1){
                //统计文档数量
                conn.setRequestMethod("POST");
            }else if (symbol==2){
                //统计所有索引
                conn.setRequestMethod("GET");
            }else{
                //GET查询
                conn.setRequestMethod("GET");
            }

//            conn.setRequestProperty("Content-Language", "en-US");
//            String input = es_username + ":" + es_password;
//            String encoding = new sun.misc.BASE64Encoder().encode(input
//                    .getBytes());
//            conn.setRequestProperty("Authorization", "Basic "
//                    + encoding);
            conn.setUseCaches(false);
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
        }
        return conn;
    }

    public HttpURLConnection getConn() {
        return conn;
    }

    public void setConn(HttpURLConnection conn) {
        this.conn = conn;
    }

    public String getTransport_addresses() {
        return transport_addresses;
    }

    public void setTransport_addresses(String transport_addresses) {
        this.transport_addresses = transport_addresses;
    }

    public String getEs_username() {
        return es_username;
    }

    public void setEs_username(String es_username) {
        this.es_username = es_username;
    }

    public String getEs_password() {
        return es_password;
    }

    public void setEs_password(String es_password) {
        this.es_password = es_password;
    }
}
